/**
 * 前端日志工具模块
 * 提供统一的日志记录功能，支持多种日志级别和环境配置
 */

// 日志级别枚举
export const LOG_LEVELS = {
  DEBUG: 0,
  INFO: 1,
  WARN: 2,
  ERROR: 3,
  NONE: 4
}

// 日志级别名称映射
const LOG_LEVEL_NAMES = {
  [LOG_LEVELS.DEBUG]: 'DEBUG',
  [LOG_LEVELS.INFO]: 'INFO',
  [LOG_LEVELS.WARN]: 'WARN',
  [LOG_LEVELS.ERROR]: 'ERROR',
  [LOG_LEVELS.NONE]: 'NONE'
}

// 日志级别颜色
const LOG_COLORS = {
  [LOG_LEVELS.DEBUG]: '#6c757d',
  [LOG_LEVELS.INFO]: '#0dcaf0',
  [LOG_LEVELS.WARN]: '#ffc107',
  [LOG_LEVELS.ERROR]: '#dc3545'
}

/**
 * 日志记录器类
 */
class Logger {
  constructor(name = 'App') {
    this.name = name
    this.level = this.getLogLevel()
    this.enableConsole = this.shouldEnableConsole()
    this.enableRemote = this.shouldEnableRemote()
    this.logs = [] // 内存中的日志缓存
    this.maxLogs = 1000 // 最大缓存日志数量
  }

  /**
   * 获取当前日志级别
   */
  getLogLevel() {
    // 从环境变量或localStorage获取日志级别
    const envLevel = import.meta.env?.VITE_LOG_LEVEL
    const storageLevel = localStorage.getItem('log_level')
    
    if (envLevel) {
      return LOG_LEVELS[envLevel.toUpperCase()] ?? LOG_LEVELS.INFO
    }
    
    if (storageLevel) {
      return parseInt(storageLevel) || LOG_LEVELS.INFO
    }
    
    // 开发环境默认DEBUG，生产环境默认ERROR
    return import.meta.env.DEV ? LOG_LEVELS.DEBUG : LOG_LEVELS.ERROR
  }

  /**
   * 是否启用控制台输出
   */
  shouldEnableConsole() {
    const envConsole = import.meta.env?.VITE_ENABLE_CONSOLE_LOG
    if (envConsole !== undefined) {
      return envConsole === 'true'
    }
    
    const storageConsole = localStorage.getItem('enable_console_log')
    if (storageConsole !== null) {
      return storageConsole === 'true'
    }
    
    // 开发环境默认启用，生产环境默认禁用
    return import.meta.env.DEV
  }

  /**
   * 是否启用远程日志
   */
  shouldEnableRemote() {
    const envRemote = import.meta.env?.VITE_ENABLE_REMOTE_LOG
    if (envRemote !== undefined) {
      return envRemote === 'true'
    }
    
    const storageRemote = localStorage.getItem('enable_remote_log')
    if (storageRemote !== null) {
      return storageRemote === 'true'
    }
    
    // 生产环境默认启用远程日志
    return !import.meta.env.DEV
  }

  /**
   * 格式化时间戳
   */
  formatTimestamp() {
    const now = new Date()
    return now.toISOString().replace('T', ' ').slice(0, 23)
  }

  /**
   * 格式化日志消息
   */
  formatMessage(level, message, data = null) {
    const timestamp = this.formatTimestamp()
    const levelName = LOG_LEVEL_NAMES[level]
    let formatted = `[${timestamp}] [${levelName}] [${this.name}] ${message}`
    
    if (data !== null && data !== undefined) {
      if (typeof data === 'object') {
        formatted += '\n' + JSON.stringify(data, null, 2)
      } else {
        formatted += ` | Data: ${data}`
      }
    }
    
    return formatted
  }

  /**
   * 记录日志到内存缓存
   */
  addToCache(level, message, data = null) {
    const logEntry = {
      timestamp: Date.now(),
      level,
      levelName: LOG_LEVEL_NAMES[level],
      logger: this.name,
      message,
      data,
      formatted: this.formatMessage(level, message, data)
    }

    this.logs.push(logEntry)
    
    // 限制缓存大小
    if (this.logs.length > this.maxLogs) {
      this.logs.shift()
    }
    
    return logEntry
  }

  /**
   * 发送远程日志
   */
  async sendRemoteLog(logEntry) {
    if (!this.enableRemote) return

    try {
      // 这里可以实现发送到远程日志服务
      // 例如发送到后端API或第三方日志服务
      const response = await fetch('/api/logs', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          ...logEntry,
          userAgent: navigator.userAgent,
          url: window.location.href,
          userId: localStorage.getItem('user_id') || 'anonymous'
        })
      })
      
      if (!response.ok) {
        // 远程日志失败时，至少在开发环境下显示错误
        if (import.meta.env.DEV) {
          console.warn('Failed to send remote log:', response.statusText)
        }
      }
    } catch (error) {
      // 远程日志失败不应该影响应用运行
      if (import.meta.env.DEV) {
        console.warn('Remote logging error:', error)
      }
    }
  }

  /**
   * 核心日志记录方法
   */
  log(level, message, data = null, error = null) {
    // 检查日志级别
    if (level < this.level) {
      return
    }

    // 添加到缓存
    const logEntry = this.addToCache(level, message, data)
    
    // 如果有错误对象，添加到日志条目中
    if (error) {
      logEntry.error = {
        name: error.name,
        message: error.message,
        stack: error.stack
      }
    }

    // 控制台输出
    if (this.enableConsole) {
      const style = `color: ${LOG_COLORS[level]}; font-weight: bold;`
      const levelName = LOG_LEVEL_NAMES[level]
      
      switch (level) {
        case LOG_LEVELS.DEBUG:
          console.debug(`%c[${levelName}]`, style, `[${this.name}]`, message, data || '')
          break
        case LOG_LEVELS.INFO:
          console.info(`%c[${levelName}]`, style, `[${this.name}]`, message, data || '')
          break
        case LOG_LEVELS.WARN:
          console.warn(`%c[${levelName}]`, style, `[${this.name}]`, message, data || '')
          break
        case LOG_LEVELS.ERROR:
          console.error(`%c[${levelName}]`, style, `[${this.name}]`, message, data || '', error || '')
          break
      }
    }

    // 发送远程日志（异步，不阻塞）
    if (this.enableRemote && level >= LOG_LEVELS.WARN) {
      this.sendRemoteLog(logEntry).catch(() => {
        // 静默处理远程日志错误
      })
    }

    return logEntry
  }

  /**
   * DEBUG级别日志
   */
  debug(message, data = null) {
    return this.log(LOG_LEVELS.DEBUG, message, data)
  }

  /**
   * INFO级别日志
   */
  info(message, data = null) {
    return this.log(LOG_LEVELS.INFO, message, data)
  }

  /**
   * WARN级别日志
   */
  warn(message, data = null) {
    return this.log(LOG_LEVELS.WARN, message, data)
  }

  /**
   * ERROR级别日志
   */
  error(message, data = null, error = null) {
    return this.log(LOG_LEVELS.ERROR, message, data, error)
  }

  /**
   * API调用日志
   */
  api(method, url, status, duration, requestData = null, responseData = null) {
    const message = `API ${method} ${url} | Status: ${status} | Duration: ${duration}ms`
    const data = {
      method,
      url,
      status,
      duration,
      requestData,
      responseData: status >= 400 ? responseData : null // 只在错误时记录响应数据
    }
    
    if (status >= 400) {
      this.error(message, data)
    } else if (status >= 300) {
      this.warn(message, data)
    } else {
      this.debug(message, data)
    }
  }

  /**
   * 用户操作日志
   */
  action(action, component, data = null) {
    const message = `User Action: ${action} in ${component}`
    this.info(message, data)
  }

  /**
   * 性能日志
   */
  performance(operation, duration, data = null) {
    const message = `Performance: ${operation} took ${duration}ms`
    if (duration > 1000) {
      this.warn(message, data)
    } else {
      this.debug(message, data)
    }
  }

  /**
   * 获取缓存的日志
   */
  getLogs(level = null, limit = 100) {
    let logs = this.logs
    
    if (level !== null) {
      logs = logs.filter(log => log.level >= level)
    }
    
    return logs.slice(-limit)
  }

  /**
   * 清空日志缓存
   */
  clearLogs() {
    this.logs = []
  }

  /**
   * 导出日志为文本
   */
  exportLogs(level = null) {
    const logs = this.getLogs(level)
    return logs.map(log => log.formatted).join('\n')
  }

  /**
   * 动态设置日志级别
   */
  setLevel(level) {
    this.level = level
    localStorage.setItem('log_level', level.toString())
    this.info(`Log level changed to ${LOG_LEVEL_NAMES[level]}`)
  }

  /**
   * 动态设置控制台输出
   */
  setConsoleEnabled(enabled) {
    this.enableConsole = enabled
    localStorage.setItem('enable_console_log', enabled.toString())
    this.info(`Console logging ${enabled ? 'enabled' : 'disabled'}`)
  }

  /**
   * 动态设置远程日志
   */
  setRemoteEnabled(enabled) {
    this.enableRemote = enabled
    localStorage.setItem('enable_remote_log', enabled.toString())
    this.info(`Remote logging ${enabled ? 'enabled' : 'disabled'}`)
  }
}

// 创建默认日志器实例
export const logger = new Logger('FlinkWeb')

// 创建特定模块的日志器
export const createLogger = (name) => new Logger(name)

// 便捷的模块日志器
export const apiLogger = createLogger('API')
export const storeLogger = createLogger('Store')
export const componentLogger = createLogger('Component')
export const routerLogger = createLogger('Router')

// 全局错误处理
window.addEventListener('error', (event) => {
  // 忽略 ResizeObserver 错误（这是 Element Plus 的已知问题，不影响功能）
  if (event.message && event.message.includes('ResizeObserver loop completed with undelivered notifications')) {
    return
  }
  
  logger.error('Global Error', {
    message: event.message,
    filename: event.filename,
    lineno: event.lineno,
    colno: event.colno
  }, event.error)
})

window.addEventListener('unhandledrejection', (event) => {
  logger.error('Unhandled Promise Rejection', {
    reason: event.reason
  })
})

// 开发环境下暴露日志器到全局
if (import.meta.env.DEV) {
  window.__LOGGER__ = logger
  window.__LOG_LEVELS__ = LOG_LEVELS
}

export default logger

